// 源插件
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DateDiff, DateStamp, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
import ReactKline from 'react-kline-pro';
// 视图插件
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import {
  Layout,
  Row,
  Col,
  Card,
  Form,
  Select,
  Input,
  message,
  Menu,
  Icon,
  AutoComplete,
} from 'antd';
// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HeaderSearch from '@/components/HeaderSearch';
import Loading from '@/components/Loading/Loading';
import $ from 'jquery';
import { parse } from 'qs';
import router from 'umi/router';
import styles from '../../components/GlobalHeader/index.less';
// css OR less预编译器

// 图片

const { Option } = AutoComplete;
const { Search } = Input;
const { SubMenu } = Menu;
const { Sider, Content } = Layout;
/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ kline, loading }) => ({
  kline,
  loading: loading.models.klineRule,
}))
@Form.create()
class Kline extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: true, // 加载状态
    symbol: 'US.BABA',
  };

  onRequestData(param, callback) {
    const that = this;
    // debugger
    $.ajax({
      type: 'GET',
      url: `http://fss.91stock.net/fss/Kline/GetKline?code=${param.symbol}`,
      contentType: 'application/x-www-form-urlencoded;charset=utf-8',
      dataType: 'json',
      async: true,
      success(data) {
        if (data.code === 1) {
          let dataCall = [];
          const coordinates = [];
          // debugger
          coordinates[0] = data.coordinates[data.coordinates.length - 1];
          dataCall = data.kline.data.item;
          callback({
            success: true,
            data: {
              lines: dataCall,
              monthCoordinates: data.monthCoordinates,
              coordinates,
              symbol: data.kline.data.symbol,
            },
          });
        }
      },
      error(e) {
        console.log(e);
      },
    });
  }

  codeUpdate(code) {
    $.ajax({
      type: 'GET',
      url: `http://fss.91stock.net/fss/Kline/GetStockInfo?code=${code}`,
      contentType: 'application/x-www-form-urlencoded;charset=utf-8',
      dataType: 'json',
      async: true,
      success(data) {
        if (data.myCode !== null) {
          that.setState({
            symbol: data.myCode,
          });
        } else {
          message.error('暂无该股票信息');
        }
      },
      error(e) {
        console.log(e);
      },
    });
    let that = this;
    /*  const { dispatch } = this.props;
      dispatch({
        type: 'kline/SearchCode',
        payload: code,
        callback: (res) => { */
    /*  if(res.code!==0){ */
    // debugger;
    /* let symbolHistory = (localStorage.getItem('symbol_history') || '').split('|');
    for (let j = 0; j < symbolHistory.length; j++) {
      if (symbolHistory[j] === code) {
        symbolHistory.splice(j, 1);
        j--;
      }
    }
    symbolHistory[symbolHistory.length] = code;
    if (symbolHistory.length > 10) {
      symbolHistory.splice(0, 1);
    }
    let toSymbolHistory = '';
    for (let i = 0; i < symbolHistory.length; i++) {
      if (i === 0) {
        toSymbolHistory = symbolHistory[0];
      } else {
        toSymbolHistory = toSymbolHistory + '|' + symbolHistory[i];
      }
    }
    localStorage.setItem('symbol_history', toSymbolHistory); */
    /*    router.push({
          pathname: '/Kline/Kline',
          // search:"code="+data.myCode,
          query: {
            symbol: code,
          },
        }); */
    /* window.querySymbol = code; */

    /*   }else{
         message.error(res.message)
       }
     }
   }); */
  }

  renderOption(item) {
    return (
      <Option key={item.code} label={item.code}>
        {`${item.market}  ${item.code}  ${item.name}`}
      </Option>
    );
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      kline: { codes },
    } = this.props;
    // let it  = router.pa
    const { dispatch } = this.props;
    const { listLoading, symbol } = this.state;
    const menu = [];
    const { querySymbol } = window;
    if (querySymbol && querySymbol !== symbol) {
      this.setState({
        symbol: querySymbol,
      });
    }

    if (localStorage.getItem('symbol_history') !== null) {
      const symbolHistory = localStorage.getItem('symbol_history').split('|');
      for (let i = 0; i < symbolHistory.length; i++) {
        const item = symbolHistory[i];
        menu[symbolHistory.length - 1 - i] = (
          <Menu.Item key={item} onClick={this.codeUpdate.bind(this, item)}>
            {item}
          </Menu.Item>
        );
      }
    }
    return (
      <PageHeaderWrapper>
        <Card>
          <div style={{ textAlign: 'left' }}>
            <HeaderSearch
              className={`${styles.action} ${styles.search}`}
              placeholder={formatMessage({ id: '股票搜索' })}
              dataSource={codes.map(this.renderOption.bind(this))}
              onChange={value => {
                dispatch({
                  type: 'kline/SearchCode',
                  payload: value,
                });
              }}
              onPressEnter={value => {
                this.codeUpdate(value);
              }}
            />
          </div>
          <br />
          <ReactKline
            // width={600}
            theme="dark"
            height={688}
            ranges={['1d']}
            symbol={symbol}
            symbolName={symbol}
            intervalTime={500000000000}
            depthWidth={100}
            // debug={true}
            onRequestData={this.onRequestData.bind(this)}
          />
          {/* <div style={{ display: '-webkit-flex', alignItems: 'flex-start' }}>
            <div style={{ flexShrink: 0, width: 220 }}>
              <Menu
                onClick={this.handleClick}
                style={{ width: 220 }}
                defaultSelectedKeys={['1']}
                defaultOpenKeys={['sub1']}
                theme="light"
                mode="inline"
                selectable={false}
              >
                <HeaderSearch
                  className={`${styles.action} ${styles.search}`}
                  placeholder={formatMessage({ id: '股票搜索' })}
                  dataSource={codes.map(this.renderOption.bind(this))}
                  onChange={value => {
                    dispatch({
                      type: 'kline/SearchCode',
                      payload: value,
                    });
                  }}
                  onPressEnter={value => {
                    this.codeUpdate(value);
                  }}
                />
                {menu}
              </Menu>
            </div>
            <div style={{ width: '100%' }}>
              <ReactKline
                // width={600}
                // height={400}
                height={688}
                ranges={['1d']}
                symbol={symbol}
                symbolName={symbol}
                intervalTime={5000000}
                depthWidth={100}
                // debug={true}
                onRequestData={this.onRequestData.bind(this)}
              />
            </div>
          </div> */}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    // this.getKline();
  }

  componentWillUnmount() {
    // debugger;
  }
}

export default Kline;
